package com.xiyuan.smartutils.xml.parser;

import com.xiyuan.smartutils.Arrays;
import com.xiyuan.smartutils.Classes;
import com.xiyuan.smartutils.StrUtils;
import com.xiyuan.smartutils.xml.Xml;
import com.xiyuan.smartutils.xml.XmlParser;
import com.xiyuan.smartutils.xml.Xmls;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.util.ArrayList;
import java.util.List;

/**
 * 数组解析器,8种基本类型数组、字符串数组和对象数组
 *
 * @version v1.1.2 @author lgz 2017-8-21 新建与整理
 */
public class ArrayParser implements XmlParser
{
    private Xml xmlMain;
    
    @Override
    public XmlParser set(Xml xmlMain)
    {
        this.xmlMain = xmlMain;
        return this;
    }
    
    @Override
    public String toStringInner(Object obj, String tagName, int tagLevel)
    {
        StringBuilder strb = new StringBuilder();
        if (tagName != null)
        {//要组号
            StrUtils.addNewLine(strb);
            StrUtils.addTwoSpace(strb, tagLevel);
            Xmls.addTagBegin(strb, tagName);
        }
        
        Object[] objs = Arrays.toArray(obj);
        for (Object o : objs)
        {
            strb.append(xmlMain.toStringInner(o, tagName, tagLevel++));
        }
        
        if (tagName != null)
        {//要组号
            StrUtils.addNewLine(strb);
            StrUtils.addTwoSpace(strb, tagLevel);
            Xmls.addTagEnd(strb, tagName);
        }
        return strb.toString();
    }

    @Override
    public Object toObjectInner(Node node, Class<?> clazz, Class<?> generics)
    {//数组类型，取组件类型不采用泛型
        if (node == null)
        {//数组如果没有返回null，这里和列表不一样，列表返回空表
            return null;
        }
        
        generics = clazz.getComponentType();
        
        List<Object> list = new ArrayList<Object>(); 
        String tagName = Xmls.getXmlClassTag(generics);
        NodeList childList = node.getChildNodes();
        for (int i=0;i<childList.getLength();i++)
        {
            Node child = childList.item(i);
            if (child.getNodeType() != Node.ELEMENT_NODE)
                continue;
            
            if (!child.getNodeName().equals(tagName))
                continue;
            
            list.add(xmlMain.toObjectInner(child, generics, null));
        }
        
        Object[] arr = Classes.newInstance(generics, list.size());
        for (int i=0;i<arr.length;i++)
        {
            arr[i] = list.get(i);
        }
        
        return arr;
    }
}
